<template>
  <div class="app-container" :style="{height:appMain.height+'px'}">
    <!--向导窗口-->
    <div class="guide-box">
      <!--标题-->
      <div class="content-title">
        <i class="el-icon-milk-tea"></i>
        <span>页面设计向导</span>
      </div>
      <!--菜单设计类型-->
      <div class="body" v-if="designStep=='home'">
        <!--创建CRUD-->
        <div class="title-box">
          <div class="item-title">创建增删改查:</div>
        </div>
        <div class="create-box">在线创建增、删、改、查、导入、导出功能。
          <div class="path-box path-input-box">
            <el-button class="btn" type="primary" @click="createCurdNext">下一步</el-button>
          </div>
        </div>
        <!--配置页面展示组件-->
        <div class="title-box">
          <div class="item-title">创建数据看板:</div>
        </div>
        <div class="create-box">在线创建一个页面，该页面包含多个数据展示组件，并对各组件分别绑定数据源。
          <div class="path-box path-input-box">
            <el-button class="btn" type="primary" @click="pageBuild">创建</el-button>
          </div>
        </div>
        <!--配置页面访问地址-->
        <div class="title-box">
          <div class="item-title">打开一个页面地址:</div>
        </div>
        <div class="path-box create-box">
          <span>是否新页面打开</span>
          <el-tooltip content="例如：网络地址【https://www.baidu.com】、项目内组件地址【error/401】以根目录views下的绝对路径" placement="top">
            <i class="el-icon-question"></i>
          </el-tooltip>
          <div style="margin-left:20px">
            <el-radio v-model="pageConfig.isFrame" label="1">否</el-radio>
            <el-radio v-model="pageConfig.isFrame" label="0">是</el-radio>
          </div>
        </div>
        <el-input v-model="pageConfig.path" placeholder="Http 或者 组件地址"></el-input>
        <div class="path-box path-input-box">
          <el-button class="btn" type="primary" @click="savePath">保存</el-button>
        </div>
      </div>
      <!--创建crud配置-->
      <div class="body" v-if="designStep=='crudConfig'">
        <!--配置页面访问地址-->
        <div class="title-box">
          <div class="item-title">请确认CRUD模块信息</div>
        </div>
        <div class="path-box create-box">
          <span>模块表名</span>
          <el-tooltip content="【数据库表名】默认为't_菜单名对应拼音'" placement="right">
            <i class="el-icon-question"></i>
          </el-tooltip>
        </div>
        <el-input v-model="pageConfig.tableName" placeholder="请输入模块标识"></el-input>

        <div class="path-box create-box">
          <span>用途描述</span>
          <el-tooltip content="【数据库表描述】简单描述当前菜单的用途" placement="right">
            <i class="el-icon-question"></i>
          </el-tooltip>
        </div>
        <el-input v-model="pageConfig.tableComment" placeholder="请输入用途描述"></el-input>
        <div class="path-box path-input-box">
          <el-button class="btn" @click="createCurdGoBack">上一步</el-button>
          <el-button class="btn" type="primary" @click="submitAddTable">提交</el-button>
        </div>

      </div>

    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import store from "@/store";
import router from "@/router";

export default {
  name: "DesignGuide",
  data() {
    return {
      //设计步骤
      designStep:'home',
      //页面配置信息
      pageConfig:{
        tabGenId: '', //表单设计Key
        buildKey: '', //表单设计Key
        isFrame:'1',//是否为外链（0是 1否）
        path: '', //路由地址
        $routerPath: '', //前端路由地址（临时使用）
        $routerName: '', //前端路由名称（临时使用）
        $routerTitle: '', //菜单名称
        createTabType: 'def',
        tableName:'',
        tableComment:''
      }
    };
  },
  created() {
    //业务模块生成ID
    this.pageConfig.buildKey = this.$route.params.tabGenId;
    if(!this.strIsNotEmpty(this.pageConfig.buildKey)){
      this.msgError("菜单配置异常，未获取到表单设计KEY");
    }
    this.pageConfig.tabGenId = this.pageConfig.buildKey;
    this.pageConfig.$routerPath = this.$router.currentRoute.path;
    this.pageConfig.$routerName = this.$router.currentRoute.name;
    this.pageConfig.$routerTitle = this.$route.meta.title;
  },
  methods: {
    /**
     * 保存路由地址
     */
    savePath(){
      if(!this.strIsNotEmpty(this.pageConfig.buildKey)){
        this.msgError("菜单配置异常，未获取到表单设计KEY");
        return;
      }
      if(!this.strIsNotEmpty(this.pageConfig.path)){
        this.msgError("请输入路由地址");
        return;
      }
      this.pageConfig['formBuildKey']=this.pageConfig.buildKey
      request({
        url: 'updateMenusPath',
        method: 'post',
        data: this.pageConfig
      }).then(res => {
        if (res.code == 200) {
          if(this.ishttp(res.data)){
            this.resetMenu(res.data);
          }else{
            this.refreshRoute();
          }
        }else{
          this.msgError(res.msg);
        }
      })

    },
    /**
     * 重置菜单
     */
    resetMenu(menuPath) {
      let that=this
      this.$modal.loading("正在重置菜单路由并刷新，请稍候...");
      store.dispatch('GenerateRoutes').then(accessRoutes => {
        // 根据roles权限生成可访问的路由表
        router.addRoutes(accessRoutes) // 动态添加可访问路由表
        setTimeout(()=>{
          that.$router.push({name:menuPath,params: { t: Date.now() } })
          that.$modal.closeLoading();
        }, 1000)
      })
    },
    refreshRoute(refPath) {
      let currentPath = this.$route.path;
      if(this.strIsNotEmpty(refPath)){
        let lastPath = this.$route.matched
        let _path="/"
        if(lastPath && lastPath.length>1){
          let _oldPathName = lastPath[lastPath.length-1]['name']
          _path = currentPath.substring(0,currentPath.indexOf(_oldPathName))
        }
        currentPath = _path + refPath

      }
      const refreshedRoute = this.$router.resolve({ path: currentPath });
      window.location.href = refreshedRoute.href;
    },
    ishttp(menuPath){
      if(menuPath==undefined){
        return false;
      }
      let _menuPath=menuPath.toLowerCase();
      if(_menuPath.startsWith("http://") || _menuPath.startsWith("https://")){
        return true;
      }
      return false;
    },
    /** 页面构建 */
    pageBuild() {
      let levels = '';
      let matcheds = this.$route.matched.filter(item => item.meta && item.meta.title)
      for(let i = 0; i < matcheds.length; i++) {
        let obj = matcheds[i];
        if(obj.meta.title){
          if(levels) levels+="/";
          levels += obj.meta.title;
        }
      }
      //是否刷新
      this.pageConfig['isRefresh']='1'
      this.pageConfig['levels']=levels
      this.$tab.openPage("[" + this.pageConfig['$routerTitle'] + "]页面构建", '/ysd/tool/PageGenerBuild/index/' + this.pageConfig['buildKey'], this.pageConfig);
    },
    /** 创建CRUD模块，进入下一步  */
    createCurdNext(){
      //业务表名
      // let fullPath = this.$router.currentRoute.path
      // fullPath = fullPath.substring(0,fullPath.indexOf(this.pageConfig.$routerName)+this.pageConfig.$routerName.length)
      // fullPath=fullPath.replace(/\//g,"_");
      // if(fullPath.startsWith("_")){
      //   fullPath = "t"+fullPath;
      // }else{
      //   fullPath = "t_"+fullPath;
      // }
      // this.pageConfig.tableName = fullPath
      this.pageConfig.tableName = "t_"+this.pageConfig.$routerName
      this.pageConfig.tableComment = this.pageConfig.$routerTitle;

      this.designStep='crudConfig'
    },
    /** 创建CRUD模块，返回上一步  */
    createCurdGoBack(){
      this.designStep='home'
    },
    /** 请求创建对应数据库表  */
    submitAddTable(){
      if(!this.strIsNotEmpty(this.pageConfig.buildKey)){
        this.msgError("菜单配置异常，未获取到表单设计KEY");
        return;
      }
      if(!this.strIsNotEmpty(this.pageConfig.tableName)){
        this.msgError("请输入模块标识");
        return;
      }
      let tableName = this.pageConfig.tableName.toLowerCase().trim();
      if(tableName.startsWith("sys_")){
        this.msgError("模块标识不能以sys_开头");
        return;
      }

      if(this.pageConfig.tableName.trim().length>64){
        this.msgError("模块标识过长，请修改");
        return;
      }


      this.pageConfig['formBuildKey']=this.pageConfig.buildKey
      let menuUrlPrex = '';
      if(this.pageConfig.$routerName.indexOf("/")>-1){
        menuUrlPrex = this.pageConfig.$routerName.substring(0,this.pageConfig.$routerName.lastIndexOf("/"))
      }
      this.pageConfig['menuUrlPrex']=menuUrlPrex
      request({
        url: 'page/gener/crud',
        method: 'post',
        data: this.pageConfig
      }).then(res => {
        if (res.code == 200) {
          this.refreshRoute(res.data.menuPath);
        }else{
          this.msgError(res.msg);
        }
      })
    }
  },
};
</script>

<style scoped>

.app-container{
  display: flex;
  align-items: center;
  justify-content: center;
}

.guide-box{
  display: flex;
  flex-direction: column;
  justify-content: center;
  background-color: #f2f2f2;
  font-size: 16px;
  width: 600px;
  box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.5);
  margin-bottom: 80px;
}

.guide-box > .content-title > .el-icon-guide{
  font-size: 40px;
}

.guide-box > .content-title {
  background-color: #304156;
  color: white;
  width: 100%;
  padding: 10px;
}

.guide-box > .content-title span {
  margin-left: 6px;
}



.guide-box > .body{
  padding: 30px;
  font-size: 14px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
}

.guide-box > .body .create{
  color: #11a983;
}
.guide-box > .body .create-box{
  margin: 10px 0;
  width: 100%;
}

.guide-box > .body .create:hover{
  cursor: pointer;
}

.guide-box > .body .path-box{
  display: flex;
  align-items: center;
}
.guide-box > .body .path-input-box{
  width: 100%;
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
/*.guide-box > .body .path-input-box .btn{*/
/*  margin-left: 10px;*/
/*}*/

.guide-box > .body .el-radio{
  margin-right:15px !important;
}


.body .title-box {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #e1e1e1;
}

.body .title-box .icon{
  margin-left: 4px;
}

.body .title-box .item-title {
  font-weight: bold;
}

</style>
